<template>



	<cl-crud ref="Crud">
		<div style="background: white;" class="demo-home">
			<el-row :gutter="10">

				<el-col :span="8">
					<count-effect :data="info" />
				</el-col>
				<el-col :span="8">
					<div class="count-sales">
						<div class="card">
							<div class="card__header">
								<span class="label">在线设备数 </span>
							</div>

							<div class="card__container">
								<cl-number :value="info?.onlineDevice" class="num" />
							</div>


						</div>
					</div>
				</el-col>

				<el-col :span="8">
					<div class="count-sales">
						<div class="card">
							<div class="card__header">
								<span class="label">离线设备数 </span>
							</div>

							<div class="card__container">
								<cl-number :value="info?.offlineDevice" class="num" />
							</div>


						</div>
					</div>
				</el-col>

			</el-row>
		</div>

		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<cl-add-btn />
			<!-- 删除按钮 -->
			<cl-multi-delete-btn />
			<cl-flex1 />
			<!-- 条件搜索 -->
			<cl-search ref="Search" />
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table">
				<template #column-code="{ scope }">
					<div style="display: flex; gap: 20px;">
						<div>
							<!-- https://ryxkeji.com?deviceNo=860835085785846A -->
							A设备
							<q-r-code-vue3
:width='200' :height="200" download
								:value="'https://ryxkeji.com?deviceNo=' + scope.row.deviceNo + 'A'" />
						</div>
						<div>
							B设备
							<q-r-code-vue3
:width='200' :height="200" download
								:value="'https://ryxkeji.com?deviceNo=' + scope.row.deviceNo + 'B'" />
						</div>
					</div>



                </template>
                <template #slot-send="{ scope }">
                    <el-button type="primary" size="small" @click="sendMs(scope.row)">设置MS数</el-button>
                </template>
            </cl-table>
        </cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="Upsert" />
	</cl-crud>
</template>


<script lang="ts" setup>

import CountUser from '../../demo/views/home/components/count-user.vue';
import CountViews from '../../demo/views/home/components/count-views.vue';
import CountPaid from '../../demo/views/home/components/count-paid.vue';
import CountEffect from '../../demo/views/home/components/count-effect.vue';



defineOptions({
	name: 'device-list'
});

import QRCodeVue3 from "qrcode-vue3";

import { useCrud, useTable, useUpsert, useSearch } from '@cool-vue/crud';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';
import { reactive, ref } from 'vue';
import UserSelect from '/$/user/components/user-select.vue';
import dayjs from 'dayjs';
import { ElMessageBox, ElMessage } from 'element-plus';

const { service } = useCool();
const { t } = useI18n();

const info = ref()

service.base.sys.info.info().then((res) => {
	console.log("resresresresres", res);
	info.value = res;

});

// 选项
const options = reactive({
	deviceStatus: [
		{ label: t('离线'), value: 0, color: 'red' },
		{ label: t('在线'), value: 1, color: 'green' },
		{ label: t('离线'), value: 2, color: 'red' }
	]
});

/* 所有商户 */
const allStore = ref<any[]>([]);

/* 获取所有role为2的用户 */
const getAgentList = async () => {
	const children = await service.user.info.list({
		role: 2
	});

	console.log("children",children);
	
	allStore.value = children?.map(_c => {
		return {
			label: `${_c.nickName ?? '-'} (手机号：${_c.phone})`,
			value: _c.id
		};
	});
};

// 所有代理
const allAgent = ref<any[]>([]);

/* 获取所有代理 */
const getAllAgent = async () => {
	const children = await service.user.info.list({
		role: 1
	});

	allAgent.value = children?.map(_c => {
		return {
			label: `${_c.nickName ?? '-'} (手机号：${_c.phone})`,
			value: _c.id
		};
	});
};

getAgentList();

getAllAgent();

// cl-upsert
const Upsert = useUpsert({
	items: [
		{
			label: t('设备编号'),
			prop: 'deviceNo',
			component: { name: 'el-input', props: { clearable: true } },
			span: 24,
			required: true
		},
		() => {
			return {
				label: '选择设备归属代理',
				prop: 'agentId',
				component: {
					name: 'el-select',
					options: allAgent,
					// 支持清空
					clearable: true,
					props: {
						clearable: true,
					}
				}
			};
		},

		() => {
			return {
				label: '选择设备归属商家',
				prop: 'userId',
				component: {
					name: 'el-select',
					options: allStore,
					clearable: true,
					props: {
						clearable: true,
					}
				},

			};
		}

	],
	async onSubmit(data, { done, close, next }) {
		next({
			...data,
			deviceNo: `${data?.deviceNo?.trim()}`
		});
	}
});

// cl-table
const Table = useTable({
	columns: [
		{ type: 'selection' },
		{ label: t('设备编号'), prop: 'deviceNo', minWidth: 120 },
		{ label: t("设备二维码"), prop: "code", minWidth: 120 },
		{ label: t('设备所属代理'), prop: 'agentNickName', minWidth: 120 },
		{ label: t('设备归属商家'), prop: 'deviceBindNickName', minWidth: 120 },

		{
			label: t('设备状态'),
			prop: 'deviceStatus',
			minWidth: 120,
			dict: options.deviceStatus
		},
		{
			label: t('最后在线时间'),
			prop: 'lastOnlineTime',
			minWidth: 170,
			sortable: 'custom',
			component: { name: 'cl-date-text' },
			render: (row) => {
				console.log('rowrowrow', row);
				if (!row.lastOnlineTime) return '-';
				return dayjs(row.lastOnlineTime * 1000).format('YYYY-MM-DD HH:mm:ss')
				// return dayjs(row.lastOnlineTime * 1000, 'YYYY-MM-DD HH:mm:ss')
			}
		},
		{
			label: t('创建时间'),
			prop: 'createTime',
			minWidth: 170,
			sortable: 'desc',
			component: { name: 'cl-date-text' }
		},
		{ type: 'op', buttons: ['slot-send', 'edit', 'delete'], width: 250 }
	],

});


// cl-search
const Search = useSearch({
	items: [
		{
			label: "状态",
			prop: "deviceStatus",
			component: {
				name: "el-select",
				options: [
					{
						label: "未激活",
						value: 0,
					},
					{
						label: "在线",
						value: 1,
					},
					{
						label: "离线",
						value: 2,
					},
				],
				props: {
					clearable: true,
				}
			},
		}, {
			label: "设备编号",
			prop: "keyWord",
			component: {
				name: "el-input",
			},

		},
		{
			label: "商户名称",
			prop: "userId",
			component: {
				name: 'el-select',
				options: allStore,
				clearable: true,
				props: {
					clearable: true,
				}
			},
		},
		{
			label: "代理名称",
			prop: "agentId",
			component: {
				name: 'el-select',
				options: allAgent,
				clearable: true,
				props: {
					clearable: true,
				}
			},
		},
	],
});

// cl-crud
const Crud = useCrud(
	{
		service: service.device.device
	},
	app => {
		app.refresh();
	}
);

// 刷新
function refresh(params?: any) {
	Crud.value?.refresh(params);
}

function sendMs(row: any) {
	ElMessageBox.prompt('请输入 ms 值', '设置ms ' + row.deviceNo, {
		confirmButtonText: '发送',
		cancelButtonText: '取消',
		inputPlaceholder: '例如 20',
		inputPattern: /^\d+$/, inputErrorMessage: '必须为数字',
	}).then(async ({ value }) => {
		// await service.request('POST', '/admin/device/device/sendMs', {
		// 	deviceNo: row.deviceNo,
		// 	ms: Number(value),
		// });
		service.device.device.sendMs({
			deviceNo: row.deviceNo,
			ms: Number(value),
		});
		ElMessage.success('发送成功');
	}).catch(() => {});
}
</script>


<style lang="scss">
.demo-home {
	overflow-x: hidden;

	.card {
		border-radius: 10px;
		margin-bottom: 10px;
		border: 1px solid var(--el-border-color-extra-light);
		background-color: var(--el-bg-color);
		color: var(--el-text-color-primary);
		user-select: none;

		&__header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 10px 20px;
			min-height: 50px;

			.label {
				font-size: 15px;
			}

			.icon {
				font-size: 30px;
				background-color: var(--el-fill-color-light);
				padding: 5px;
				border-radius: 6px;
			}
		}

		&__container {
			padding: 0 20px;
			min-height: 50px;

			.num {
				font-size: 32px;
			}
		}

		&__footer {
			display: flex;
			align-items: center;
			height: 50px;
			margin: 0 5px;
			padding: 0 15px;
			box-sizing: border-box;
			font-size: 12px;

			.label {
				margin-right: 10px;
			}
		}
	}
}
</style>
